import time
import os
from multiprocessing import cpu_count
import fileinput
import csv


class NodeResource(object):
    def __init__(self,root_path,hostname):
        self.root_path = root_path
        self.hostname = hostname

    def cpu_speed(self):
        with fileinput.input(self.root_path + '/cpuinfo') as f:
            for line in f:
                if 'MHz' in line:
                    value = line.split(':')[1].strip()
                    value = float(value)
                    speed = round(value)
                    return speed


    def usage_percent(self,use, total):
        # 返回百分占比
        try:
            ret = int(float(use)/ total * 100)
        except ZeroDivisionError:
            raise Exception("ERROR - zero division error")
        return ret

    @property
    def cpu_stat(self,interval = 1):

        cpu_num = cpu_count()
        with open(self.root_path + "/stat", "r") as f:
            line = f.readline()
            spl = line.split(" ")
            worktime_1 = sum([int(i) for i in spl[2:]])
            idletime_1 = int(spl[5])
        time.sleep(interval)
        with open(self.root_path + "/stat", "r") as f:
            line = f.readline()
            spl = line.split(" ")
            worktime_2 = sum([int(i) for i in spl[2:]])
            idletime_2 = int(spl[5])

        dworktime = (worktime_2 - worktime_1)
        didletime = (idletime_2 - idletime_1)
        cpu_percent = self.usage_percent(dworktime - didletime,didletime) / 100
        cpu_free = round((self.cpu_speed() * cpu_num ) - (self.cpu_speed() * cpu_num * cpu_percent))
        # print( {'cpu_count':cpu_num,
        #         'cpu_percent':cpu_percent,
        #         'cpu_total': self.cpu_speed() * cpu_num,
        #         'cpu_free': cpu_free})
        return cpu_free

    @property
    def disk_stat(self):
        hd = {}
        disk = os.statvfs('/')
        hd['available'] = round(disk.f_bsize * disk.f_bfree / 1024 /1024)
        hd['capacity'] = round(disk.f_bsize * disk.f_blocks/ 1024 /1024)
        hd['used'] =  hd['capacity'] - hd['available']
        hd['used_percent'] = (self.usage_percent(hd['used'], hd['capacity']))
        return hd['available']

    @property
    def memory_stat(self):
        mem = {}
        with open(self.root_path + "/meminfo") as f:
            for line in f:
                line = line.strip()
                if len(line) < 2: continue
                name = line.split(':')[0]
                var = line.split(':')[1].split()[0]
                mem[name] = int(var) * 1024.0
            mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached']
        mem['used_percent'] = self.usage_percent(mem['MemUsed'],mem['MemTotal'])
        # print({'MemUsed': round(mem['MemUsed'] /1024/1024) ,'MemTotal': round(mem['MemTotal'] /1024/1024),'used_percent':mem['used_percent']})
        return round((mem['MemTotal'] - mem['MemUsed']) /1024/1024)

    @property
    def data(self):
        file = open("/opt/train/data.csv",'r')
        reader = csv.reader(file)
        lines = len(list(reader))
        return lines

# nr = NodeResource(root_path='/proc',hostname='node1')
#
# print (nr.cpu_stat)
# print (nr.disk_stat)
# print (nr.memory_stat)
# print (nr.data_stat)
# print (nr.hostname)
# print (nr.data_increase)